package org.pc2r.game.model;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class SubMarine implements Iterable<Position> {

  private boolean isHorizontal;
  private List<Position> positions;
  private Player player;

  public SubMarine(List<Position> positions, boolean isHorizontal) {
    this.isHorizontal = isHorizontal;
    this.positions = positions;
  }

  public SubMarine(int x, int y, int size, boolean isHorizontal) {
    this.isHorizontal = isHorizontal;
    this.positions = new ArrayList<>();
    for (int i = 0; i < size; i++) {
      if (this.isHorizontal) {
        positions.add(new Position(x + i, y));
      } else {
        positions.add(new Position(x, y + i));
      }
    }
  }

  public boolean isHorizontal() {
    return isHorizontal;
  }

  public boolean isSuperposed(SubMarine sub) {
    for (Position position : this) {
      if (sub.isTouched(position)) {
        return true;
      }
    }
    return false;
  }

  public boolean isTouched(int x, int y) {
    return isTouched(new Position(x, y));
  }

  public boolean isTouched(Position position) {
    return positions.contains(position);
  }

  public boolean touch(int x, int y) {
    for (Position pos : positions) {
      if (pos.getX() == x && pos.getY() == y) {
        pos.setTouched(true);
        return true;
      }
    }
    return false;
  }

  public boolean isDead() {
    for (Position pos : positions) {
      if (pos.isTouched() == false)
        return false;
    }
    return true;
  }

  @Override
  public Iterator<Position> iterator() {
    return positions.iterator();
  }

  public Player getPlayer() {
    return player;
  }

  public void setPlayer(Player player) {
    this.player = player;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + (this.isHorizontal ? 1231 : 1237);
    result = prime * result + ((this.player == null) ? 0 : this.player.hashCode());
    result = prime * result + ((this.positions == null) ? 0 : this.positions.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    SubMarine other = (SubMarine) obj;
    if (this.isHorizontal != other.isHorizontal)
      return false;
    if (this.player == null) {
      if (other.player != null)
        return false;
    } else if (!this.player.equals(other.player))
      return false;
    if (this.positions == null) {
      if (other.positions != null)
        return false;
    } else if (!this.positions.equals(other.positions))
      return false;
    return true;
  }
}
